/*
 * @Author       : wangzhenguo
 * @Date         : 2021-03-22 17:20:44
 * @LastEditors  : wangzhenguo
 * @LastEditTime : 2021-03-22 17:37:07
 * @Description  : 权限验证
 */
import router from "./index";
import NPregress from "nprogress";
import "nprogress/nprogress.css";
import nProgress from "nprogress";

NPregress.configure({
  easing: "ease",
  speed: 500, //递增进度条的速度
  showSpinner: false, //是否显示加载ico
  trickleSpeed: 200, //自动递增间隔
  minimum: 0.3, //初始化时的最小百分比
});

const cancelAxios = (next) => {
  let axiosPromiseArr = window.__axiosPromiseArr;
  if (!!axiosPromiseArr && axiosPromiseArr.length) {
    let len = axiosPromiseArr.length;
    while (len--) {
      axiosPromiseArr[len].cancel("cancel");
      axiosPromiseArr.splice(len, 1);
    }
  }

  next();
};

router.beforeEach((to, from, next) => {
  // 每次切换时调用进度条
  if (to.matched.some((r) => r.meta.requiresAuth)) {
    if (!sessionStorage.getItem("token")) {
      next({
        path: "/nopermission",
        query: {
          redirect: to.fullPath,
        },
      });
    } else {
      cancelAxios(next);
    }
  } else {
    cancelAxios(next);
  }
});

router.afterEach((to) => {
  // 在即将进入新的页面时关闭进度条
  nProgress.done();
  document.title = to.name || "";
});

export default router;
